package pers.cz.chat.filter;

import io.netty.channel.Channel;
import io.netty.util.internal.StringUtil;
import pers.cz.chat.GroupManager;
import pers.cz.chat.UserManager;
import pers.cz.netty.filter.FilterHandler;
import pers.cz.netty.filter.FilterHandlerContext;
import pers.cz.netty.protocal.Message;
import pers.cz.netty.protocal.MsgType;


/**
 * @version 1.0
 * @description: 展示在线用户拦截器
 * @author: ChengZhi 0336
 * @create: 2025-01-06 18:14
 **/
public class ShowUsersFilter implements FilterHandler<Message, Channel> {

	@Override
	public boolean approve(Message message, Channel channel, FilterHandlerContext<Message, Channel> handlerContext) {

		if (MsgType.SHOW.equals(message.getMsgType())) {
			StringBuilder users = new StringBuilder("\n");
			users.append("当前在线用户：\n");
			UserManager.getOnlinUser().forEach(user -> {
				users.append(user).append("\n");
			});

			users.append("我的群聊：\n");
			String username = message.getAttachment("username");
			if (!StringUtil.isNullOrEmpty(username)) {
				GroupManager.getMyGroup(username).forEach(groupName -> {
					users.append(groupName).append("\n");
				});
			}

			Message loginSuccessMessage = new Message();
			loginSuccessMessage.setMsgType(MsgType.SHOW);
			loginSuccessMessage.addAttachment("source", "server");
			loginSuccessMessage.setContent(users.toString());
			channel.writeAndFlush(loginSuccessMessage);
			return true;
		}
		return handlerContext.doFilter(message, channel);
	}
}
